﻿using System;
using System.IO.IsolatedStorage;
using System.Windows.Forms;
using System.IO;

namespace isolatedstorage
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void BtnCreateUserFile_Click(object sender, EventArgs e)
        {
            // Create a New File in Isolated Storage

            // First, we need to get the isolated store for the USER
            // (since we don't want user files to be available to everyone.
            // Since we are are not a ClickOne app, we can only get UserStoreForAssembly.
            var userStore = IsolatedStorageFile.GetUserStoreForAssembly();

            var fileStream = new IsolatedStorageFileStream(
                "UserFile.txt", FileMode.Create, userStore);

            // Write some text to the file.
            StreamWriter writer= new StreamWriter(fileStream);
            writer.WriteLine(string.Format(
                "I am data put in to isolated storage at {0}!", DateTime.Now.ToLocalTime()));
            writer.Close();

            MBox.Info("File Created/Updated!");
        }

        private void BtnReadingFiles_Click(object sender, EventArgs e)
        {
            // Get the Isolated Store.
            var isolatedStore = IsolatedStorageFile.GetUserStoreForAssembly();

            // Check to see if the file exists.
            if (IsolatedFileExists("UserFile.txt", isolatedStore))
            {
                // Open up the file and get its data.
                var fileStream = new IsolatedStorageFileStream(
                    "UserFile.txt", FileMode.Open, isolatedStore);

                StreamReader reader = new StreamReader(fileStream);
                var s = reader.ReadToEnd();
                reader.Close();

                MBox.Info(s, "Data in UserFile.txt");
            }
            else
            {
                MBox.Error("File Not Found! Did you click \"Creating Files\"?", "UserFile.txt Not Found");
            }
        }

        private bool IsolatedFileExists(string fileName, IsolatedStorageFile store)
        {
            // Get the Files in the Store.
            var files = store.GetFileNames(fileName);
            return (files.Length != 0);
        }
    }
}